package web.servlet;


import com.alibaba.fastjson.JSON;
import com.pzhu.pojo.Brand;
import com.pzhu.pojo.PageBean;
import com.pzhu.service.BrandService;
import com.pzhu.service.impl.BrandServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;

@WebServlet("/brand/*")
public class BrandServlet extends BaseServlet{

    BrandService brandService = new BrandServiceImpl();
//添加一条记录
    public void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        BufferedReader reader = req.getReader();
        //1拿 到了post请求所传输的brand数据，json字符串
        String s = reader.readLine();
        //2将json字符串转换为对象
        Brand brand = JSON.parseObject(s, Brand.class);
        //3调用service中的add()添加数据到数据库表中
        brandService.add(brand);
        //通过resp带回成功标识
        resp.getWriter().write("success");
    }
//查询所有记录
    public void selectAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        //查询所有数据
        List<Brand> brands = brandService.selectAll();
        //通过JSON.toJSONString把对象转换为字符串
        String s = JSON.toJSONString(brands);

        resp.setContentType("text/json;charset=utf-8");

        resp.getWriter().write(s);
    }

    /**
     * 分页查询
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void selectByPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        //http://localhost:8088/mybrand-demo2/brand/selectByPage?currentPage=1&pageSize=5
//        根据请求参数拿到查询页码
        int currentPage = Integer.parseInt(req.getParameter("currentPage"));
        //        根据请求参数拿到查询每页条目数
        int pageSize = Integer.parseInt(req.getParameter("pageSize"));
//        获得查询的当前页开始索引位置
        int begin = (currentPage-1)*pageSize;
        int size = pageSize;
        PageBean<Brand> pageBean = brandService.selectByPage(begin, size);
//        将pageBean转换成json字符串
        String s = JSON.toJSONString(pageBean);
        resp.setContentType("text/json;charset=utf-8");
//        把分页查询结果返回到页面
        resp.getWriter().write(s);

    }



//删除
    public void deleteByIds(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        BufferedReader reader = req.getReader();
        //1拿 到了post请求所传输的ids数据，json字符串
        String s = reader.readLine();
        //2将json字符串转换为数组
        int[] ids = JSON.parseObject(s, int[].class);

        brandService.deletByIds(ids);

        resp.getWriter().write("success");

    }

}
